package com.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.util.Util;



@Controller
@RequestMapping("/upload")
public class UploadController {

	
	// 获取输出对象
	public PrintWriter getPrintWriter(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return writer;
	}
	

	@RequestMapping(value = "/image", method = RequestMethod.POST)
	public void image(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestParam("filedata") MultipartFile file) throws	Exception {

		// 将图片按日期分开存放，方便管理

		final	String prefix = "uploads/"+ Util.getRiqi();

		// 存放到web根目录下,如果日期目录不存在，则创建,

		// 注意 request.getRealPath("/") 已经标记为不推荐使用了.

		final	String realPath = session.getServletContext().getRealPath(prefix);

		File dir = new File(realPath);

		if(!dir.exists()) {

			dir.mkdirs();

		}

		// 取得原文件名

		String originName = file.getOriginalFilename();

		// 取得文件后缀

		String fileExt = originName.substring(originName.lastIndexOf(".") + 1);

		// 按时间戳生成图片文件名

		String picture = Util.getTime2() + "."+ fileExt;

		try{

			IOUtils.copy(file.getInputStream(),new FileOutputStream(new File(dir, picture)));

		}catch(Exception e) {

		}

		String http = "http://"+ request.getServerName()+":"+ request.getServerPort()+ request.getContextPath();  

		String url =  http + "/"+ prefix + "/"+ picture;

		PrintWriter writer = this.getPrintWriter(response);
		
		writer.println("{\"err\":\"\",\"msg\":\""+url+"\"}");

	}
}












